package com.fzkj.concurrent;

/**
 * 两阶段终止模式
 */
public class TwoPhaseTermination {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTer twoPhaseTer = new TwoPhaseTer();
        twoPhaseTer.start();
        Thread.sleep(3000);
        twoPhaseTer.stop();
    }
}

class TwoPhaseTer {
    private Thread monitor;

    /**
     * 启动监控线程
     */
    public void start (){
        monitor = new Thread(() -> {
            while(true){
                Thread current = Thread.currentThread();
                if (current.isInterrupted()) {
                    System.out.println("停止前操作");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    System.out.println("执行监控操作");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    // 睡眠过程中被打断，会抛出异常，重新设置打断标记
                    monitor.interrupt();
                }
            }
        }, "");
        monitor.start();
    }

    /**
     * 停止监控方法
     */
    public void stop() {
        if (null != monitor) monitor.interrupt();
    }

    /**
     * isInterrupted() : 不会清除打断标记
     * interrupted() : 会清除打断标记
     */

}
